<template>
  <div class="base-container" id="main">
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
    </t-loading>
    <div>
      <!-- 基本信息 -->
      <t-form ref="form" class="step-form" :colon="true" :data="formData" @submit="onSubmit" :rules="rules" labelWidth="180px">
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-card class="step-card" size="small" title="基本信息">
              <t-form-item label="任务来源" name="taskSource">
                <t-input clearable style="width: 390px" v-model="formData.taskSource"></t-input>
              </t-form-item>
              <t-form-item label="计划标准编号" name="projectNum">
                <t-input style="width: 390px" clearable v-model="formData.projectNum"></t-input>
              </t-form-item>
              <t-form-item label="主要起草单位" name="unitId">
                <t-tree-select clearable filterable style="width: 390px" :treeProps="{ keys: { value: 'id' } }"
                  v-model="formData.unitId" :data="deptMenuOptions" placeholder="选择主管单位单位"></t-tree-select>
              </t-form-item>
            </t-card>
          </t-col>
        </t-row>

        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-form-item :show-error-message="false" name="draftPersons" label="起草小组成员" labelAlign="top">
              <member-list :editOpen="true" :objId="localId" ref="declaration-description" v-model="formData.draftPersons"></member-list>
            </t-form-item>
          </t-col>
        </t-row>
        <t-form-item name="technologyIndex" labelAlign="top" label="标准主要技术性能指标，与国际标准和国外先进标准的对比分析及对标准水平的分析（起草小组填写）">

          <tiny-mce-editor :textLength.sync="lengthLimitObj.declarationDescription"
            v-model="formData.technologyIndex"></tiny-mce-editor>
        </t-form-item>
        <t-form-item name="expectedGoal" labelAlign="top" label="标准经济效益或社会效益的分析（起草小组填写）">

          <tiny-mce-editor :textLength.sync="lengthLimitObj.declarationDescription"
            v-model="formData.expectedGoal"></tiny-mce-editor>
        </t-form-item>
        <t-form-item name="suggestion" labelAlign="top" label="贯彻标准的措施建议">

          <tiny-mce-editor :textLength.sync="lengthLimitObj.declarationDescription"
            v-model="formData.suggestion"></tiny-mce-editor>
        </t-form-item>
        <t-row>
          <t-col :span="12">
            <t-form-item name="fileUpload" label="上传报审相关文件" labelAlign="top" style="padding-bottom: 10px">
              <t-table row-key="id" :columns="projectFileColumns" :data="projectFileData">
                <template #id="{row, rowIndex}">
                  {{ rowIndex+1 }}
                </template>
                <template #op="{row}">
                  <file-upload accept="application/pdf,image/*" v-model="row.fileIds" :moduleKey="row.moduleKey"
                               :fileList="row.fileLists"
                               :multiple="true" tips="限制pdf、图片">
                    <t-button variant="outline">
                      <t-icon name="cloud-upload" slot="icon"/>
                      点击上传
                    </t-button>
                  </file-upload>
                </template>
                <template #c1="{row}">
                  <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
                  <div v-else>{{row.c1}}</div>
                </template>
              </t-table>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="12" class="query-form-inline">
            <t-button theme="primary" @click="subType=1" type="submit">暂存</t-button>
            <t-tooltip content="提交后不可再编辑会进入报审流程">
              <t-button theme="primary"  @click="subType=2" type="submit">提交报审</t-button>
            </t-tooltip>
          </t-col>
        </t-row>
      </t-form>
    </div>
  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import { getDictList } from "@/api/system/dict/data";
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";
import memberList from "../../components/member-list.vue";
import FileUpload from "@/components/FileUpload/index.vue";
import dayjs from "dayjs";
import {getFiles} from "@/api/common";

export default {
  name: "form-my",
  dicts:[],
  components: {
    TinyMceEditor,
    // declarationDescription2,
    FileUpload,
    memberList
  },
  data() {
    return {
      site_tag: import.meta.env.VITE_SITE_TAG,
      file_domain: VITE_FILE_DOMAIN,
      localId: null,
      profTitOptions: [],
      subType:1,
      projectFileData: [
        {
          id: 1,
          c1: "报审表一式三份（盖好相应章）",
          c2: "是",
          moduleKey: "projectBSB",
          fileIds: [],
          fileLists: [],
        },
        {
          id: 2,
          c1: "报审标准文本",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectBSBZWB"
        },
        {
          id: 3,
          c1: "报审编制说明",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectBZSM"
        },
        {
          id: 4,
          c1: "报审征求意见汇总表",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectBSZQYJ"
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      deptMenuOptions: [],
      applyLoading: false,
      maxlength: 1000,
      lengthLimitObj: {
        declarationDescription: 0
      },
      tinymceFlag: 1,
      dayjs,
      dictTypes: {},
      formData: {
        localId: null,
        taskSource: "",
        projectNum: "",
        unitId: null,
        draftPersons: [],
        technologyIndex: "",
        expectedGoal: "",
        suggestion: "",
      },
      rules: {
        taskSource: [
          {
            required: true,
            message: "任务来源不能为空",
          },
        ],
        // fileUpload: [
        //   { required: true, message: "计划标准编号不能为空" }
        // ],
        projectNum: [
          { required: true, message: "任务来源/计划项目编号不能为空" }
        ],
        unitId: [
          {
            required: true,
            message: "主要起草单位不能为空",
          },
        ],
        draftPersons: [
          {
            required: true,
            message: "起草小组成员不能为空",
          },
        ],
        technologyIndex: [
          {
            required: true,
            message: "标准主要技术性能指标不能为空",
          },
        ],
        expectedGoal: [
          {
            required: true,
            message: "标准经济效益或社会效益的分析不能为空",
          },
        ],
        suggestion: [
          {
            required: true,
            message: "贯穿标准的措施建议不能为空",
          },
        ],
      },
    }
  },
  async created() {
    const localId = this.$route.params && this.$route.params.taskId;
    if (!localId) {
      this.$message.error("缺少标准id");
      return false;
    }
    this.localId = localId;
    this.formData.localId = localId;
    this.getDetail();
    this.getDeptTreeSelect();
  },
  methods: {
    async getDetail() {
      await getFiles(this.localId).then((res) => {
        const files = {}
        res.data.forEach((item) => {
          if (!files[item.moduleKey]) {
            files[item.moduleKey] = []
          }
          files[item.moduleKey].push({
            name: item.fileName,
            url: item.fullFilePath,
            id: item.id,
            filePath: item.filePath
          })
        })
        this.projectFileData.forEach((val,index)=>{
          this.projectFileData[index].fileLists = files[val.moduleKey] || [];
          this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
        })

      }).catch((e) => {
        this.$message.error(e.toString());
      });
      const res = await this.$api.bzh.report.getByLocalId(this.localId)
      // Object.assign(this.formData, res.data);
      this.formData = Object.assign({}, this.formData, res.data)
    },
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getDataTypes() {
      return getDictList(["formulate_type"]).then(response => {
        this.dictTypes = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onSubmit({ validateResult, firstError }) {
      if(this.subType===1 ||  validateResult===true){
        if(this.subType===2){
          if (this.projectFileData[0].fileIds.length <= 0) {
            this.$message.error("需要上传报审表一式三份（盖好相应章）");
            return false;
          }
          if (this.projectFileData[1].fileIds.length <= 0) {
            this.$message.error("需要上传报审标准文本");
            return false;
          }
          if (this.projectFileData[2].fileIds.length <= 0) {
            this.$message.error("需要上传报审编制说明");
            return false;
          }
          if (this.projectFileData[3].fileIds.length <= 0) {
            this.$message.error("需要上传报审征求意见汇总表");
            return false;
          }
        }
        const sysAttMainIds = []
        this.projectFileData.forEach(val=>{
          sysAttMainIds.push(...val.fileIds)
        })
        // this.formData.sysAttMainVo = {
        //   sysAttMainIds
        // }
        this.formData.approveStatus = this.subType
        if(this.subType===1){
          this.$api.bzh.standard.updateForFile({
            id: this.localId,
            sysAttMainVo: {
              sysAttMainIds
            }
          }).then(response => {
            if(this.formData.id){
              this.$api.bzh.reportTrial.update(this.formData).then(response=>{
                this.$message.success("暂存成功")
                this.$router.push("/bzh/report/report-my")
              }).catch(e=>{
                this.$message.error(e.toString())
              })
            }else {
              this.$api.bzh.reportTrial.add(this.formData).then(response=>{
                this.$message.success("暂存成功")
                // this.$router.push("/bzh/report/report-my")
              }).catch(e=>{
                this.$message.error(e.toString())
              })
            }
          }).catch(e => {
            this.subBtnLoading =false
            this.$message.error(e.toString())
          })

        }else{
          this.$api.bzh.standard.updateForFile({
            id: this.localId,
            sysAttMainVo: {
              sysAttMainIds
            }
          }).then(response => {
            this.$api.bzh.reportTrial.submit(this.formData).then(response=>{
              this.$message.success("提交成功")
              this.$router.push("/bzh/report/report-my")
            }).catch(e=>{
              this.$message.error(e.toString())
            })
          }).catch(e => {
            this.subBtnLoading =false
            this.$message.error(e.toString())
          })
        }
      }else{
        this.$message.error(firstError)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>

